package com.uptown.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: Lixiaofei
 * @date: 2020/5/3 15:41
 */
public class BIOServer {

    public static void main(String[] args) throws Exception{
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        //服务端scoket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器已启动");
        while(true){
            //等待客户端连接
            System.out.println("等待连接。。");
            //accept为阻塞方法
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            //创建线程通讯
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    //与客户端通信
                    handler(socket);
                }
            });
        }
    }
    //编写一个handler方法
    public static void handler(Socket socket){

        //通过socket获取输入流
        try {
            System.out.println("线程信息 id ="+Thread.currentThread().getId()
                    +"名字"+Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while(true){
                System.out.println("线程信息 id ="+Thread.currentThread().getId()
                        +"名字"+Thread.currentThread().getName());
                System.out.println("read阻塞");
               int read = inputStream.read(bytes);
               if(read != -1){
                   System.out.println(new String(bytes,0,read));
               }else{
                   break;
               }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和client的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
